package com.mate.cloud.lottery.service.stock;

import com.mate.cloud.lottery.constants.LotteryConstants;
import com.mate.cloud.lottery.constants.LotteryExceptionCodeEnum;
import com.mate.cloud.lottery.exception.UnRewardException;
import com.mate.cloud.lottery.mapper.LotteryPrizeMapper;
import com.mate.cloud.lottery.service.AsyncLotteryRecordTask;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @description: java类作用描述
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/1/24 13:28
 * @updateUser: MI
 * @updateTime: 2025/1/24 13:28
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Service
public class HasStockRewardProcessor extends AbstractRewardProcessor {
    @Resource
    AsyncLotteryRecordTask asyncLotteryRecordTask;

    @Resource
    LotteryPrizeMapper lotteryPrizeMapper;




    @Override
    protected void afterProcessor(RewardContext context) {
        asyncLotteryRecordTask.saveLotteryRecore(context.getAccountIp(), context.getLotteryItem(), context.getPrizeName());
    }

    @Override
    protected int getAwardType() {
        return LotteryConstants.PrizeTypeEnum.NORMAL.getValue();
    }

    @Override
    protected void processor(RewardContext context) {
        // 扣减库存（redis更新）
        Long stockNum = redisTemplate.opsForHash().increment(context.getKey(), "validStock", -1);
        if (stockNum.intValue() <= 0) {
            throw new UnRewardException(LotteryExceptionCodeEnum.LOTTER_REPO_NOT_ENOUGHT.getCode());
        }
        List<Object> propertys = Arrays.asList("id", "prizeName");
        List<Object> prizes = redisTemplate.opsForHash().multiGet(context.getPrizeId(), propertys);
        context.setPrizeId(Integer.parseInt(prizes.get(0).toString()));
        context.setPrizeName(prizes.get(1).toString());
        // 更新库存（mysql更新）
        lotteryPrizeMapper.updateValidStock(context.getPrizeId());

    }

}
